package info.jafe.common.context;

import android.app.Application;
import android.content.Context;
import android.os.Handler;
import android.support.annotation.UiThread;

import info.jafe.common.exception.UnRegisteredException;


/**
 * Created by jafe chang on 2016/12/10.
 */

public class ContextProvider {
    private static ContextProvider sProvider;
    private Handler mHandler;
    private Application mApplication;

    private ContextProvider(){}

    private static synchronized ContextProvider getsProvider(){
        if (sProvider == null) {
            synchronized (ContextProvider.class){
                if (sProvider == null) {
                    sProvider = new ContextProvider();
                }
            }
        }
        return sProvider;
    }

    @UiThread
    public static void onCreate(Application application){
        ContextProvider provider = getsProvider();
        provider.mApplication = application;
        provider.mHandler = new Handler();
    }

    public static Application getApplication(){
        return sProvider.mApplication;
    }

    public static Context getContext(){
        try {
            return sProvider.mApplication.getApplicationContext();
        } catch (NullPointerException ignore){
            throw new UnRegisteredException(UnRegisteredException.APPLICATION_UNREGISTERED);
        }
    }

    public static Handler getHandler() {
        try {
            return sProvider.mHandler;
        } catch (NullPointerException ignore) {
            throw new UnRegisteredException(UnRegisteredException.APPLICATION_UNREGISTERED);
        }
    }

}
